<template>
  <el-dialog v-el-drag-dialog :title="!form.jobId?'新建任务':'编任务'" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-form ref="taskForm" :model="form" :rules="rules" label-width="120px" :disabled="!hasLoaded">
      <el-form-item hidden>
        <el-input v-model="form.jobId" hidden />
      </el-form-item>

      <el-card>
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" />
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-input v-model="form.jobGroup" />
        </el-form-item>
        <el-form-item label="任务方法" prop="methodName">
          <el-input v-model="form.methodName" />
        </el-form-item>
        <el-form-item label="方法参数" prop="methodParam">
          <el-input v-model="form.methodParam" />
        </el-form-item>
        <el-form-item label="执行表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression">
            <template v-if="hasLoaded" slot="append">
              <el-button type="primary" @click="handleShowCron">
                生成表达式
                <i class="el-icon-time el-icon--right"></i>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="计划策略" prop="misfirePolicy">
          <el-select v-model="form.misfirePolicy">
            <el-option
              v-for="item in optionOfPolicy"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="并发执行" prop="concurrent">
          <el-radio-group v-model="form.concurrent">
            <el-radio v-for="item in optionOfConcurrent" :key="item.dictCode" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button v-for="item in optionOfStatus" :key="item.dictCode" :label="item.dictValue" :disabled="item.dictValue !== form.status">{{ item.dictLabel }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-card>
    </el-form>

    <el-dialog title="Cron表达式生成器" :visible.sync="openCronDialog" append-to-body class="scrollbar" destroy-on-close>
      <crontab @hide="openCronDialog=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { quartzLoad, quartzSave } from '@/api/tool/quartz'
import Crontab from '@/components/Crontab'

export default {
  components: {
    Crontab
  },
  name: 'QuartzFormDialog',
  data() {
    const validateJobName = (rule, value, callback) => {
      if (value === undefined || value === '') {
        rule.message = '任务名称不能为空'
        return callback(new Error(rule.message))
      }

      this.$http.get(`${process.env.VUE_APP_MODULE_ADMIN_API}/api/system/job/checkJobName`, {
        params: {
          jobId: this.form.jobId,
          jobName: value
        }
      }).then(response => {
        if (response.valid) {
          callback()
        } else {
          rule.message = '已存在任务名称'
          callback(new Error(rule.message))
        }
      }).catch(() => {
        callback()
      })
    }
    const validateJobGroup = (rule, value, callback) => {
      if (value === undefined || value === '') {
        rule.message = '任务组名不能为空'
        return callback(new Error(rule.message))
      }

      this.$http.get(`${process.env.VUE_APP_MODULE_ADMIN_API}/api/system/job/checkJobGroup`, {
        params: {
          jobId: this.form.jobId,
          jobGroup: value
        }
      }).then(response => {
        if (response.valid) {
          callback()
        } else {
          rule.message = '已存在任务组名'
          callback(new Error(rule.message))
        }
      }).catch(() => {
        callback()
      })
    }
    const validateCron = (rule, value, callback) => {
      if (value === undefined || value === '') {
        rule.message = '执行表达式不能为空'
        return callback(new Error(rule.message))
      }

      this.$http.get(`${process.env.VUE_APP_MODULE_ADMIN_API}/api/system/job/checkCronExpression`, {
        params: {
          cronExpression: value
        }
      }).then(response => {
        if (response.valid) {
          callback()
        } else {
          rule.message = '执行表达式格式不正确'
          callback(new Error(rule.message))
        }
      }).catch(() => {
        callback()
      })
    }

    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      form: {
        jobId: undefined,
        jobName: undefined,
        jobGroup: undefined,
        methodName: undefined,
        methodParam: undefined,
        cronExpression: undefined,
        misfirePolicy: '1',
        concurrent: '1',
        status: '3'
      },
      rules: {
        jobName: [{
          required: true,
          trigger: 'blur',
          validator: validateJobName
        }],
        jobGroup: [{
          required: true,
          trigger: 'blur',
          validator: validateJobGroup
        }],
        methodName: [{ required: true, message: '任务方法不能为空' }],
        cronExpression: [{
          required: true,
          trigger: 'blur',
          validator: validateCron
        }]
      },
      expression: undefined,
      optionOfStatus: [],
      optionOfPolicy: [],
      optionOfConcurrent: [],
      openCronDialog: false
    }
  },
  methods: {
    init(jobId) {
      this.hasLoaded = false
      this.form.jobId = jobId || null
      this.visible = true
      this.$nextTick(() => {
        this.getDictData()
        this.loadForm(jobId)
      })
    },
    loadForm(jobId) {
      quartzLoad({ 'id': jobId }).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        // 判断当前用户权限
        this.hasLoaded = this.$perm.hasPermissionOr(['tool:quartz:edit'])
      }).catch(() => {})
    },
    getDictData() {
      const that = this
      this.$http.all([this.$dictGroup('sys_execute_method'),
            this.$dictGroup('sys_quartz_concurrent'),
            this.$dictGroup('sys_quartz_status')])
        .then(this.$http.spread((policy, concurrent, status) => {
          that.optionOfPolicy = policy
          that.optionOfConcurrent = concurrent
          that.optionOfStatus = status
      })).catch(e => {})
    },
    handleShowCron() {
      this.expression = this.form.cronExpression
      this.openCronDialog = true
    },
    crontabFill(value) {
      this.form.cronExpression = value
    },
    onSubmit() {
      this.$refs.taskForm.validate(valid => {
        if (valid) {
          quartzSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.onClose()
          }).catch(() => {})
        }
      })
    },
    onClose() {
      this.$refs.taskForm.resetFields()
      this.visible = false
    }
  }
}
</script>
